package demo.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileTypeUtil;
import com.alibaba.fastjson.JSON;
import demo.constant.Constants;
import demo.dao.SimpleFileDao;
import demo.entity.FileEntity;
import demo.service.SimpleFileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Date;
import java.util.UUID;

@Service
public class SimpleFileServiceImpl implements SimpleFileService {

    SimpleFileDao simpleFileDao;

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${file.dest}")
    private String dest;

    @Autowired
    public SimpleFileServiceImpl(SimpleFileDao simpleFileDao) {
        this.simpleFileDao = simpleFileDao;
    }

    @Override
    public String upload(MultipartFile file) {
        if (file.isEmpty()) {
            return Constants.UPLOAD_FAIL_MESSAGE;
        }

        Date nowDate = new Date();
        String fileName = file.getOriginalFilename();
        String fileUUID = UUID.randomUUID().toString();
        String fileCode = fileUUID + fileName.substring(fileName.lastIndexOf("."));
        String dirUrl = dest + "\\" + DateUtil.format(nowDate, "yyyyMMdd");
        String fileUrl = dirUrl + "\\" + fileCode;
        File newFile = new File(dirUrl, fileCode);

        try {
            if (!newFile.exists()) {
                newFile.mkdirs();
            }
            file.transferTo(newFile);
        } catch (IOException e) {
            return Constants.UPLOAD_FAIL_MESSAGE;
        }

        FileEntity fileEntity = new FileEntity();
        fileEntity.setCode(fileUUID);
        fileEntity.setName(fileName);
        fileEntity.setSize(file.getSize());
        fileEntity.setType(FileTypeUtil.getType(newFile));
        fileEntity.setInsertTime(nowDate);
        fileEntity.setUrl(fileUrl);

        simpleFileDao.save(fileEntity);

        logger.info("文件上传成功:" + fileName);
        return fileUUID;
    }

    @Override
    public ResponseEntity download(String uuid) throws IOException {
        if (null == uuid) {
            return new ResponseEntity(HttpStatus.GONE);
        }

        FileEntity file = simpleFileDao.findUrlByUUID(uuid);
        if (null == file) {
            return new ResponseEntity(HttpStatus.GONE);
        }

        InputStream is = new FileInputStream(file.getUrl());
        byte[] bytes = new byte[is.available()];
        is.read(bytes);
        MultiValueMap<String, String> headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment;filename=" + file.getCode() + file.getName().substring(file.getName().lastIndexOf(".")));
        is.close();
        logger.info("文件下载成功:" + file.getName());
        return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
    }

    @Override
    public String getFileInfo(String uuid) {
        FileEntity file = simpleFileDao.findUrlByUUID(uuid);
        return JSON.toJSONString(file);
    }
}
